import React, { FC, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { SwipeAction, SearchBar } from 'antd-mobile-v2';
import styles from './index.module.less';
import { Props, State } from '../../../type';
import { GetProvideList } from '@/services/laber-declare';
import AntdRefreshList from '@/components/antd-refresh-list';
import EmptyRefresh from '@/components/empty/empty-refresh';
import classnames from 'classnames';
import { DETAIL_MODE } from '@/plugins/form/form-components/laber-detail/constants';

let debounceTimer = null; // 搜索防抖计时器

export interface DetailModal extends Props {
  onLaberEdit?: (index) => void;
  onLaberDelete?: (index) => void;
  addModal?: () => void;
  form: any;
  value: any[];
  onCloseModal: () => void;
  detailMode?: State['detailMode'];
}

export interface GetDataListParams {
  id?: string;
  list: any[];
  pageNum?: number;
  source?: DETAIL_MODE.EXPORT | DETAIL_MODE.NO_EXPORT; // 明细列表展示模式（1-导入 2-人工录入）
  keyWord?: string;
}

const detailModal: FC<DetailModal> = (props) => {
  const [values, setValues] = useState([] as any[]);
  const [showValues, setShowValues] = useState([] as any[]);
  const [keyword, setKeyword] = useState<string>();
  const [showDom, setshowDom] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [pageNum, setPageIndex] = useState(1);


  useEffect(() => {
    handleRefresh();
  }, [props.value]);

  useEffect(() => {
    if (keyword === undefined) return;
    searchListByKeyword(keyword);
  }, [keyword]);

  const getSearchName = (name) => {
    const locationStr = location.hash?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return obj?.[name] || '';
  };

  const onOpen = (index) => {
    console.log('global open', index);
  };

  const onClose = () => {
    console.log('global close');
  };

  const rightBtns = (index: number) => {
    return [
      {
        text: '修改',
        onPress: () => onLaberEdit(index),
        style: { backgroundColor: '#C7C7CC', color: 'white', fontSize: '18px', padding: '7px' }
      },
      {
        text: '删除',
        onPress: () => onLaberDelete(index),
        style: { backgroundColor: '#FF3A30', color: 'white', fontSize: '18px', padding: '7px' }
      }
    ];
  };

  const getDescript = (index: number) => {
    const standard = values[index]?.standard?.text?.split(' ')[0] || values[index]?.standardName || '';
    const standardId = values[index]?.standard?.value || values[index]?.standardId;
    const price = values[index]?.price || '';
    const unit = values[index]?.unit?.text || '';
    let quantity = values[index]?.quantity || 0;
    if (quantity % 1 !== 0) {
      quantity = (<span style={{ color: '#FF8800' }}>{quantity}</span>);
    }
    if (!standardId) {
      return (
        <div style={{ color: '#FF8800' }}>{standard + ' ' + price + unit + ' *'}{quantity}</div>
      );
    }
    return (
      <>{standard + ' ' + price + unit + ' *'}{quantity}</>
    );
  };

  // 删除
  const onLaberDelete = (index: number) => {
    props.onLaberDelete && props.onLaberDelete(index);
  };

  // 打开修改弹窗
  const onLaberEdit = (index: number) => {
    props.onLaberEdit && props.onLaberEdit(index);
  };

  const searchChange = (value: string) => {
    setKeyword(value);
  };

  const searchListByKeyword = async (value: string) => {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(async () => {
      setRefreshing(true);
      await getDataList({ id: '', list: [], pageNum: 1, keyWord: value });
      setRefreshing(false);
      clearTimeout(debounceTimer);
    }, 0.8 * 1000);
  };

  const getDataList = async (params: GetDataListParams) => {
    setRefreshing(true);
    const reportId = getSearchName('applyId');
    let res: any = { data: {} };
    if (reportId && props.detailMode === DETAIL_MODE.EXPORT) {
      const data = {
        reportId: reportId,
        source: props.detailMode
      };
      res = await GetProvideList(data);
    } else {
      res = {
        data: {
          rows:props.value || []
        }
      };
    }
    setshowDom(true);
    const list = filterKeyWord(params.keyWord, res.data?.rows || []);
    console.log(list);
    setValues(list);
    setShowValues(list);
  };

  const filterKeyWord = (keyWord: string, list: any[]): any[] => {
    const reg = new RegExp(keyWord);
    console.log('list', list);
    return list?.filter((item: any) => {
      if (props.detailMode === DETAIL_MODE.EXPORT) {
        return reg.test(item.studentCode) || reg.test(item.studentName);
      } else {
        const studentCode = item.studentCode?.value || item.studentCode;
        const studentName = item.studentCode?.studentName || item.studentName;
        return reg.test(studentCode) || reg.test(studentName);
      }
    });
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    await getDataList({ id: '', list: [], pageNum: 1, keyWord: keyword });
    setRefreshing(false);
  };

  const formatNumber = (num: number): number | string => {
    const length = num.toString()?.split('.')[1]?.length;
    if (length >= 2) {
      return num?.toFixed(2);
    }
    return num;
  };

  const handleLoadMore = async () => {
    const index = pageNum + 1;
    setPageIndex(index);
    const reportId = getSearchName('applyId');
    let res: any = { data: {} };
    if (reportId) {
      const data = {
        reportId: reportId,
        pageNum: index,
        pageSize: 10
      };
      res = await GetProvideList(data);
      const list = filterKeyWord('', res.data?.rows || []);
      setValues([...values, ...list]);
      setShowValues([...showValues, ...list]);

    }
  };

  return (
    <div className={styles.detailModalWrapper}>
      <div className={styles.searchWrap}>
        <SearchBar
          placeholder="开户姓名/证件号"
          value={keyword}
          onChange={searchChange}
        />
      </div>
      {
        values?.length > 0 ?
          <div className={classnames(styles.laberDetailWrapper, props.renderMode === 'detail' || props.detailMode === 1 ? styles.noFooter : '')}>
            <AntdRefreshList
              dataSource={showValues}
              refreshing={refreshing}
              // loadingMore={loadingMore}
              renderRow={(item, sectionID, index) => (
                <div key={item.id + index}>
                  <SwipeAction
                    style={{ backgroundColor: 'gray' }}
                    right={rightBtns(index)}
                    onOpen={() => onOpen(index)}
                    onClose={() => onClose()}
                    disabled={props.renderMode == 'detail' || props.detailMode === DETAIL_MODE.EXPORT}
                  >
                    <div className={styles.laberDetailContent}>
                      <div className={styles.title}>
                        <span className={styles.titleLeft}>{item?.studentName || item?.studentCode?.studentName}</span>
                        <span className={styles.titleRight}>{formatNumber(item?.provideAmount) || 0}元</span>
                      </div>
                      <div className={styles.content}>
                        <span className={styles.contentLeft}>{item?.studentCode?.value}</span>
                        <span className={styles.contentRight}>{getDescript(index)}</span>
                      </div>
                      <div className={styles.remark}>
                        备注：{item?.remark || '无'}
                      </div>
                    </div>
                  </SwipeAction>
                </div>
              )}
              // onRefresh={handleRefresh}
              onEndReached={handleLoadMore}
            />
          </div>
          : (
            <EmptyRefresh
              refreshing={refreshing}
            // onRefresh={handleRefresh}
            />
          )
      }

      {/* <Button type="primary" className={styles.confirmBtn} onClick={props.onCloseModal && props.onCloseModal()}>
          关闭
        </Button> */}
      {/* {
        props.renderMode === 'detail' || props.detailMode === 1 // 申报详情模式，或者导入类型的明细列表，不显示添加按钮
          ? null
          :
          <div className={styles.footer}>
            <Button type="primary" className={styles.confirmBtn} onClick={onLaberAdd}>+ 添加发放明细</Button>
          </div >
      } */}
    </div>
  );
};

export default connect()(detailModal);
